#
# @lc app=leetcode.cn id=703 lang=python3
#
# [703] 数据流中的第 K 大元素
#

# @lc code=start
import heapq

class KthLargest:
    pq = None
    def __init__(self, k: int, nums: List[int]):
        self.size = k
        self.heap = nums[0:]
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)
            
    def add(self, value: int) -> int:
        if len(self.heap) < self.size:
            heapq.heappush(self.heap, value)
        elif value > self.heap[0]:
            heapq.heapreplace(self.heap, value) # 这个方法等价于下面两个方法，效率更高。
            # heapq.heappop(self.heap)
            # heapq.heappush(self.heap, value)
        return self.heap[0]

# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
# @lc code=end

